//
//  webToolbar.m
//  WebViewPopMenu
//
//  Created by GZMLUser on 15-1-12.
//  Copyright (c) 2015年 GZMLUser. All rights reserved.
//

#import "webToolbar.h"

#define BUTTON_WITH 36
#define BUTTON_HEIGTH 36

#define BUTTON_MARGIN 4 // 边距
#define BUTON_SPACING 8

#define BOTTOM_BUTTON_WIDTH 40
#define BOTTOM_BUTTON_HEIGTH 20
@implementation ToolbarItem

+ (id)itemWithImage:(UIImage *)image title:(NSString *)title
{
    return [[self alloc]initWithTitle:title image:image highlightImage:nil];
}

+ (id)itemWithImage:(UIImage *)image highlightImage:(UIImage *)highlightedImage
{
    return [[self alloc]initWithTitle:nil image:image highlightImage:highlightedImage];
}

+ (id)itemWithTitle:(NSString *)title
{
    return [[self alloc]initWithTitle:title image:nil highlightImage:nil];
}


- (id)initWithImage:(UIImage *)image highlightImage:(UIImage *)highlightedImage
{
    return [self initWithTitle:nil image:image highlightImage:highlightedImage];
}

- (id)initwithTitle:(NSString *)title
{
    return [self initWithTitle:title image:nil highlightImage:nil];
}

- (id)initWithImage:(UIImage *)image title:(NSString *)title
{
    return [self initWithTitle:title image:image highlightImage:nil];
}


- (id)initWithTitle:(NSString *)title image:(UIImage *)image highlightImage:(UIImage *)highlightedImage
{
    self = [super init];
    
    if(self) {
        self.title = title;
        self.image = image;
        self.highlightedImage = highlightedImage;
    }
    
    return self;
}

@end


@implementation webToolbar
{
    UIView *toolbarView; // 放置Item
    UIButton *bottomBtn; // 底部按钮
}

- (id)initWithItems:(NSArray *)itemsArray frame:(CGRect)frame 
{
    if (self = [super initWithFrame:frame]) {

        // 设置底部button
        [self buildBottomButtonWithFrame:frame];
        
        // 根据数组计算界面
        [self buildToolbarViewWithItems:itemsArray];
        
    }
    return self;
}
- (id)initWithItem:(ToolbarItem *)item  frame:(CGRect)frame
{
    NSArray *tempArray = [NSArray arrayWithObject:item];
    
    return [self initWithItems:tempArray frame:frame];
}
#pragma mark - 设置底部按钮
- (void)buildBottomButtonWithFrame:(CGRect)frame
{
    bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    // 放置superview底部
//    [bottomBtn.layer setCornerRadius:3.0f];
//    [bottomBtn.layer setMasksToBounds:YES];
//    
    [bottomBtn setFrame:CGRectMake((CGRectGetWidth(self.bounds) - BOTTOM_BUTTON_WIDTH) / 2, CGRectGetHeight(self.bounds) - BOTTOM_BUTTON_HEIGTH + 3, BOTTOM_BUTTON_WIDTH, BOTTOM_BUTTON_HEIGTH)];
    
    [bottomBtn setImage: [self image:[UIImage imageNamed:@"commonWebView_pull_shangc"] rotation:UIImageOrientationUp] forState:UIControlStateNormal];
    
    
    [bottomBtn addTarget:self action:@selector(bottomButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:bottomBtn];
}

#pragma mark - 底部按钮点击处理
- (void)bottomButtonClicked:(UIButton *)sender
{
    if (toolbarView.hidden == YES) {
        [self showToolbarView];
    }
}


#pragma 设置toolbarView
- (void)buildToolbarViewWithItems:(NSArray *)itemsArray
{
    toolbarView = [[UIView alloc]initWithFrame:self.bounds];
    toolbarView.backgroundColor = [UIColor clearColor];
    toolbarView.hidden = YES;
    
    // 设置背景透明图片
    UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:self.bounds];
    bgImageView.contentMode = UIViewContentModeScaleToFill;
    
    bgImageView.image = [self getPartOfImage:[UIImage imageNamed:@"bg_mask.png"] rect:CGRectMake(100, 0, CGRectGetWidth(toolbarView.bounds) - 200, CGRectGetHeight(toolbarView.bounds))];
    [toolbarView addSubview:bgImageView];

    
    // 添加左边Item
    CGFloat itemLoc = BUTON_SPACING;
    if (itemsArray.count > 0) {
        for (int i = 0; i<itemsArray.count; i++) {
            
            ToolbarItem *item = itemsArray[i];
            
            
            UIButton *btn = [self buttonWithItem:item frame:CGRectMake(itemLoc, BUTTON_MARGIN, BUTTON_WITH, BUTTON_HEIGTH)];
            itemLoc = CGRectGetMaxX(btn.frame) + BUTON_SPACING;
            
            btn.tag = i; // 索引
            [toolbarView addSubview:btn]; // toolbarview添加Item
        }
        
    }
    
    // 添加右边Item
    [toolbarView addSubview:[self addRightButton]];

    [self addSubview:toolbarView]; // 添加toolbarView
}

#pragma mark 设置左边Item
- (UIButton *)buttonWithItem:(ToolbarItem *)toolbarItem frame:(CGRect)frame
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    
    
    if (toolbarItem.title != nil) {
        [button setTitle:toolbarItem.title forState:UIControlStateNormal];

        if (toolbarItem.image != nil) {
            [self adjustButtonchildViews:button];
            [button setImage:toolbarItem.image forState:UIControlStateNormal];
            [button setImage:toolbarItem.highlightedImage forState:UIControlStateHighlighted];
        }
        
    } else {
        
        [button setBackgroundImage:toolbarItem.image forState:UIControlStateNormal];
        [button setBackgroundImage:toolbarItem.highlightedImage forState:UIControlStateHighlighted];
    }
    [button addTarget:self action:@selector(itemClicked:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

#pragma mark - 右边固定Item
- (UIButton *)addRightButton
{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setFrame:CGRectMake(CGRectGetWidth(self.bounds) - (BUTTON_WITH + BUTON_SPACING), BUTTON_MARGIN, BUTTON_WITH, BUTTON_HEIGTH)];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"commonWebView_drop_shangc"] forState:UIControlStateNormal];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"commonWebView_drop_shangc_hl"] forState:UIControlStateHighlighted];
    [rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    return rightButton;
}

#pragma mark - item点击事件
- (void)itemClicked:(UIButton *)item
{
    if ([self.delegate respondsToSelector:@selector(webToobarItemClicked:itemIndex:)]) {
        [self.delegate webToobarItemClicked:self itemIndex:item.tag];
    }
}

#pragma mark - 右边固定Item点击事件
- (void)rightButtonClicked:(UIButton *)sender
{
    
    if (toolbarView.hidden == NO) {
        [self hideToolbarView];
    }
}

- (void)hideToolbarView
{
    if (toolbarView.hidden == NO)
    {
        bottomBtn.hidden = NO;
        [UIView animateWithDuration:0.25 delay:0.0
                            options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
                         animations:^(void)
         {
             toolbarView.alpha = 0.0f;
         }
                         completion:^(BOOL finished)
         {
             toolbarView.hidden = YES;
         }
         ];
    }
}

- (void)showToolbarView
{
    if (toolbarView.hidden == YES)
    {
        bottomBtn.hidden = YES;
        [UIView animateWithDuration:0.25 delay:0.0
                            options:UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction
                         animations:^(void)
         {
             toolbarView.hidden = NO;
             toolbarView.alpha = 1.0f;
         }
                         completion:NULL
         ];
    }
}

#pragma mark - 调整button内部图片和文字的位置

- (void)adjustButtonchildViews:(UIButton *)button
{
    button.imageEdgeInsets = UIEdgeInsetsMake(-8,0,8,0);
   
    button.titleLabel.font = [UIFont systemFontOfSize:14];//title字体大小
    button.titleLabel.textAlignment = NSTextAlignmentCenter;//设置title的字体居中
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];//设置title在一般情况下为白色字体
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];//设置title在button被选中情况下为灰色字体
    button.titleEdgeInsets = UIEdgeInsetsMake(20, -CGRectGetWidth(button.bounds)*2-10, 0, 0);
}

#pragma mark - 获取图片部分图片处理
- (UIImage *)getPartOfImage:(UIImage *)img rect:(CGRect)partRect
{
    CGFloat scale = [[UIScreen mainScreen] scale];
    CGRect scaledRect = CGRectMake(partRect.origin.x * scale, partRect.origin.y * scale, partRect.size.width * scale, partRect.size.height);
    CGImageRef imageRef = img.CGImage;
    CGImageRef imagePartRef = CGImageCreateWithImageInRect(imageRef, scaledRect);
    UIImage *retImg = [UIImage imageWithCGImage:imagePartRef];
    CGImageRelease(imagePartRef);
    return retImg;
}

#pragma mark - 改变图片方向
- (UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation
{
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    
    switch (orientation) {
        case UIImageOrientationLeft:
            rotate = M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = 0;
            translateY = -rect.size.width;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationRight:
            rotate = 3 * M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = -rect.size.height;
            translateY = 0;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationDown:
            rotate = M_PI;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = -rect.size.width;
            translateY = -rect.size.height;
            break;
        default:
            rotate = 0.0;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = 0;
            translateY = 0;
            break;
    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    return newPic;
}


@end
